package kr.hayarobee.jaringobi.model.account;

import kr.hayarobee.jaringobi.exception.AccountClosedException;
import kr.hayarobee.jaringobi.exception.AccountNotEmptyException;
import kr.hayarobee.jaringobi.exception.NotEnoughMoneyException;
import kr.hayarobee.jaringobi.model.account.rule.AccountPolicy;

public class BankAccount implements Account {

	private boolean closed;
	private AccountPolicy policy;
	
	public BankAccount() {
		this.closed = false;
	}
	
	public void setAccountPolicy(AccountPolicy policy) {
		this.policy = policy;
	}

	@Override
	public int checkBalance() {
		verifyAccountClosed();
		return this.policy.get();
	}

	@Override
	public void deposit(int money) {
		verifyAccountClosed();
		this.policy.add(money);
	}

	@Override
	public void withdrawal(int money) {
		verifyAccountClosed();
		this.policy.del(money);
	}
	
	private void verifyAccountClosed() {
		if (this.closed)
			throw new AccountClosedException();
	}

	public void merge(BankAccount other) {
		int money = other.checkBalance();
		other.withdrawal(money);
		deposit(money);
		other.closed();
	}

	public void closed() {
		if (this.policy.get() != 0)
			throw new AccountNotEmptyException();
		this.closed = true;
	}

	public boolean isClosed() {
		return this.closed;
	}

	public void open() {
		this.closed = false;
	}
}
